<?php

namespace JsonLowCode\Form\Fields;

use Closure;
use JsonLowCode\UI\Radio;
use JsonLowCode\Form\Abstract\FieldAbstract;
use JsonLowCode\Form\Traits\HasDisabled;
use JsonLowCode\Form\Traits\HasSize;

/**
 * @property Radio $element
 */
class RadioField extends FieldAbstract
{

    use HasDisabled, HasSize;

    protected bool $group = false;

    protected mixed $options = [];

    private ?Closure $labelClosure = null;

    protected function booting(): void
    {
        $this->element = new Radio();
        $this->element->name($this->field);
    }

    /**
     * @param array $options
     * @return $this
     */
    public function options(array $options = []): static
    {
        $this->options = $options;
        return $this;
    }

    /**
     * @param bool $bool
     * @return $this
     */
    public function button(bool $bool = true): static
    {
        $this->element->button($bool);
        return $this;
    }

    /**
     * @param Closure $closure
     * @return $this
     */
    public function labelClosure(Closure $closure): static
    {
        $this->labelClosure = $closure;
        return $this;
    }

    protected function setOptions(): void
    {
        $options = [];
        foreach ($this->options as $key=>$option){
            if (!is_array($option)){
                $option = ['label'=>$option,'value'=> $key];
            }
            if ($this->labelClosure!=null){
                $result = call_user_func($this->labelClosure, $option);
                if ($result){
                    $option = $result;
                }
            }
            $options[] = $option;
        }
        $this->element->options($options);
    }

    protected function render(): void
    {
        $this->setOptions();
    }
}
